#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

#define BUFFER_SIZE 3
#define MAX_ITEMS 10

int buffer[BUFFER_SIZE];
int count=0;
int front=0;
int rear=0; 

pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t not_full=PTHREAD_COND_INITIALIZER;
pthread_cond_t not_empty=PTHREAD_COND_INITIALIZER;

void *producer(void*) {
    for (int i=1;i<=MAX_ITEMS;i++) {
        pthread_mutex_lock(&mutex);
        while(count==BUFFER_SIZE) {
            pthread_cond_wait(&not_full,&mutex);
        }

        buffer[rear]=i;
        rear=(rear+1)%BUFFER_SIZE;
        count++;
        printf("生产者放入:%d(队列大小: %d)\n",i,count);
        pthread_cond_signal(&not_empty);
        pthread_mutex_unlock(&mutex);
        usleep(300000);
    }
    return (0);
}
void* consumer(void*) {
    for (int i=0; i<MAX_ITEMS;i++) {
        pthread_mutex_lock(&mutex);
        while(count==0) {
            pthread_cond_wait(&not_empty,&mutex);
        }
        int item=buffer[front];
        front=(front+1)%BUFFER_SIZE;
        count--;
        printf("\t消费者取出:%d(队列大小:%d)\n",item,count);
        pthread_cond_signal(&not_full);
        pthread_mutex_unlock(&mutex);
        usleep(400000);
    }
    return NULL;
}

int main() {
    pthread_t prod_thread, cons_thread;
    pthread_create(&prod_thread, NULL, producer, NULL);
    pthread_create(&cons_thread, NULL, consumer, NULL);
    pthread_join(prod_thread, NULL);
    pthread_join(cons_thread, NULL);
    printf("\n所有%d个物品生产消费完成\n",MAX_ITEMS);
    return 0;
}


